package com.qkbb.admin.kuibu.qkbb.Servers;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.util.Log;

import com.qkbb.admin.kuibu.R;
import com.qkbb.admin.kuibu.qkbb.Step.StepDcretor;
import com.qkbb.admin.kuibu.qkbb.activity.Theme;
import com.qkbb.admin.kuibu.qkbb.funcation.CountDownTimer;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class StepServers extends Service implements SensorEventListener {
    private int steps;
    private SimpleDateFormat format;
    private String date;
    private SharedPreferences sharedPreferences;
    public static int CURRENT_SETP = 0;

    public static float SENSITIVITY = 0;   //SENSITIVITY灵敏度

    private float mLastValues[] = new float[3 * 2];
    private float mScale[] = new float[2];
    private float mYOffset;
    private static long end = 0;
    private static long start = 0;
    private static int duration = 30000;

    /**
     * 最后加速度方向
     */
    private float mLastDirections[] = new float[3 * 2];
    private float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] };
    private float mLastDiff[] = new float[3 * 2];
    private int mLastMatch = -1;
    private Handler handler;
    NotificationManager manager;
    private Notification notification;
    private Notification.Builder builder;
    private SensorManager sensorManager;
    private boolean flag;
    private StepDcretor stepDetector;
    private PowerManager.WakeLock mWakeLock;
    private TimeCount time;
    private int i;
    private SharedPreferences.Editor editor;
    private int SDsteps;
    private int BaseSteps;
    private int num;
    private int year;
    private int month;
    private int day;

    public StepServers() {
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        super.onCreate();
        sharedPreferences=getSharedPreferences("step", Activity.MODE_PRIVATE);
        editor=sharedPreferences.edit();
        getData();
        SDsteps=sharedPreferences.getInt(date, 0);
        BaseSteps=SDsteps;
        initBroadcastReceiver();
        updateNotification("今日步数" + SDsteps + "");
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (num>=100){
                    num=0;
                    editor.putInt(date, SDsteps);
                    editor.commit();
                }
                num++;

                        Log.e(date, date);
                        Log.e("sharedPreferences", sharedPreferences.getInt(date, 0) + "");
                Log.e("fasrg", "ahra");
            }
        };
        Log.e("BaseSteps", BaseSteps+"");
        Log.e("onCreate", "onCreate");
    }
    private void initBroadcastReceiver(){
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DATE_CHANGED);
        BroadcastReceiver receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                getData();
                Log.e("日期改变", date);
                BaseSteps=0;
                SDsteps=0;
                getData();
                updateNotification("今日步数："+SDsteps);
            }
        };
        registerReceiver(receiver,filter);
    }
    private void getData() {
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        if (date==null) {
            date = String.valueOf(year) + String.valueOf(month) + String.valueOf(day);
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void updateNotification(String title) {
        builder=new Notification.Builder(this);
        PendingIntent pendingIntent=PendingIntent.getActivity(this,0,new Intent(this, Theme.class),0);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.drawable.kuibulogo);
        builder.setOngoing(true);
        builder.setContentTitle(title);
        notification=builder.build();
        startForeground(0, notification);
        manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0, notification);
        int h = 480;
        mYOffset = h * 0.5f;
        mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2)));
        mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX)));

    }

//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//
//        int flag=START_REDELIVER_INTENT;
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                startStepDetector();
//            }
//        }).start();
//        Log.e("onStartCommand", "onStartCommand");
//        return super(intent,flag,startId);
//    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int flag=START_REDELIVER_INTENT;
        new Thread(new Runnable() {
            @Override
            public void run() {
                startStepDetector();
            }
        }).start();

        Log.e("onStartCommand", "onStartCommand");
        return super.onStartCommand(intent, flag, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy","onDestroy");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startStepDetector() {
        if (sensorManager != null && stepDetector != null) {
            sensorManager.unregisterListener(stepDetector);
            sensorManager = null;
            stepDetector = null;
        }
        getLock(this);
        if (sensorManager == null) {
            stepDetector = new StepDcretor(this);
            // 获取传感器管理器的实例
            sensorManager = (SensorManager) this
                    .getSystemService(SENSOR_SERVICE);
            // 获得传感器的类型，这里获得的类型是加速度传感器
            // 此方法用来注册，只有注册过才会生效，参数：SensorEventListener的实例，Sensor的实例，更新速率
            Sensor sensor = sensorManager
                    .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            // sensorManager.unregisterListener(stepDetector);
            sensorManager.registerListener(stepDetector, sensor,
                    SensorManager.SENSOR_DELAY_UI);
            stepDetector
                    .setOnSensorChangeListener(new StepDcretor.OnSensorChangeListener() {

                        @Override
                        public void onChange() {
                            Log.e("CURRENT_SETP",CURRENT_SETP+"");
                            CURRENT_SETP=StepDcretor.CURRENT_SETP;
                            SDsteps=BaseSteps+CURRENT_SETP;
                            Log.e("SDsteps", SDsteps + "");
                            updateNotification("今日步数：" + SDsteps + " 步");
                            Message message=new Message();
                            message.what=1;
                            handler.sendMessage(message);


                        }
                    });
        }

        //android4.4以后可以使用计步传感器
        sensorManager = (SensorManager) this
                .getSystemService(SENSOR_SERVICE);
        Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        if (countSensor != null) {
            sensorManager.registerListener(StepServers.this, countSensor, SensorManager.SENSOR_DELAY_UI);
        } else {
            Log.v("xf","Count sensor not available!");
        }
    }
    synchronized private PowerManager.WakeLock getLock(Context context) {
        if (mWakeLock != null) {
            if (mWakeLock.isHeld())
                mWakeLock.release();
            mWakeLock = null;
        }

        if (mWakeLock == null) {
            PowerManager mgr = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    StepServers.class.getName());
            mWakeLock.setReferenceCounted(true);
            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(System.currentTimeMillis());
            int hour = c.get(Calendar.HOUR_OF_DAY);
            if (hour >= 23 || hour <= 6) {
                mWakeLock.acquire(5000);
            } else {
                mWakeLock.acquire(300000);
            }
        }

        return (mWakeLock);
    }
    private void startTimeCount() {
        time = new TimeCount(duration, 1000);
        time.start();
    }
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            // 如果计时器正常结束，则开始计步
            time.cancel();
//            save();
            startTimeCount();
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }

    }

    @Override
    public void onSensorChanged(SensorEvent event) {

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}